import {http} from '@/hos/http'
import {base64} from '@/hos/base64'

/**
 * @enum {{WX: number, EMAIL: number}}
 */
let LoginWay = {
    WX: 0 /* 微信登陆 */, EMAIL: 1 /* 邮箱登陆 */
}
/**
 * @static
 */
class api {
    static bindSession3rd (host, session3rd, loginWay) {
        this._host = host
        this._session3rd = session3rd
        this._loginWay = loginWay
    }

    static post (url, data, fun1, fun2) {
        url = this._host + '/' + url
        // alert(url)
        let session3rd = this._session3rd
        let loginWay = this._loginWay
        let date = Math.round(new Date().getTime() / 1000)
        let option = {}
        let requestData = {}
        if (loginWay === LoginWay.WX) { // 微信登录
            option = {
                'headers': {
                    'reqTimestamp': date + '',
                    'txnSubType': '00',
                    'session3rd': session3rd
                },
                'timeout': 30
            }
            requestData = data
        } else { // 邮箱登录
            requestData = JSON.parse(JSON.stringify(data)) // 传值
            let sign
            data.reqtimestamp = date
            let newkey = Object.keys(data).sort()
            newkey = newkey.reverse() // 键值排序,从大到小
            data.app_key = 'henortekapp'
            newkey.push('app_key')
            let str = ''
            newkey.map(function (item) {
                str += `${item}=${encodeURIComponent(data[item])}&`
            })
            str = str.substring(0, str.length - 1)
            sign = base64.encode(str)
            requestData.reqtimestamp = date
            requestData.cmd_key = session3rd
            requestData.sign = sign
        }
        console.log(requestData)
        return http.post(url, requestData, option).then(function (res) {
            console.log(res)
            if (res.code === 40001 || res.code === 40000 || res.code === 40006 || res.code === 40004) {
                console.log('ssion3rd过期', res)
                fun2(res)
            } else {
                fun1(res)
            }
        }, function (res) {
            console.log('失败', res)
            fun2(res)
        })
    }
}

export {api, LoginWay}
